import { Component } from '@angular/core';

import { NavController, ViewController} from 'ionic-angular';

import { Storage } from '@ionic/storage';

import { Common } from "../../../providers/common";
import {CirculateService} from "./circulate.service";

import _ from "lodash";

@Component({
	selector: 'modal-ipm-circulate',
	templateUrl: 'circulate.modal.html',
  providers: [CirculateService]
})
export class IpmCirculateModal{

  moa_page_name: any = "modal-ipm-circulate";
  moa_page_explain: any = "组合管理 - 基金列表";

  fundList = null;

  isSelectAll = false;

  isNoMoreData = false;

  fundType = "-1";

  selectOne = false

	constructor(
		public navCtrl: NavController,
    public common: Common,
    private circulateService: CirculateService,
    public viewCtrl: ViewController,
    public storage: Storage
	) {
    this.selectOne = this.viewCtrl.getNavParams().get("selectOne") ?
      this.viewCtrl.getNavParams().get("selectOne") : false;
  }

  radioSelected(item) {
    this.viewCtrl.dismiss(item);
  }

  selectAll() {
	  if (this.isSelectAll) {
      _.forEach(this.fundList, fund => {
        fund["selected"] = true;
      });
    } else {
      _.forEach(this.fundList, fund => {
        fund["selected"] = false;
      });
    }
  }

  ionViewDidEnter() {
	  this.storage.get("userInfo").then(user => {
      let selectedFund = this.viewCtrl.getNavParams().get("selectedFund");
      this.fundType = this.viewCtrl.getNavParams().get("fundType") ?
        this.viewCtrl.getNavParams().get("fundType") : "-1";

      this.circulateService.getFundList(user.loginid, this.fundType).subscribe(dataList => {
        console.log(dataList);
        if (dataList) {
          this.fundList = dataList;
          if (this.fundList.length <= 0) {
            this.isNoMoreData = true;
          }
          _.forEach(this.fundList, fund => {
            let temp = _.find(selectedFund, {vc_fund_code: fund.vc_fund_code});
            if (temp) {
              fund["selected"] = true;
            } else {
              fund["selected"] = false;
            }
          });

          if (this.fundList.length == selectedFund.length) {
            this.isSelectAll = true;
          }
        } else {
          this.isNoMoreData = true;
        }
      });
    });
  }

  closeModal() {
    this.viewCtrl.dismiss("close");
  }

  completeModal() {
	  let list = _.filter(this.fundList, {selected: true});
	  this.viewCtrl.dismiss(list);
  }


}

